#pragma once
#include "../comm/log.hpp"
#include <string>
#include <unordered_map>
#include <assert.h>
#include <vector>
#include<fstream>
#include"../comm/util.hpp"
#include <stdlib.h>
#include"../comm/log.hpp"

// 题目加载到内存
namespace ns_model
{

    using namespace std;
    using namespace ns_util;
    using namespace ns_log;
    struct Question
    {

        std::string number; // 编号
        std::string title;  // 题目标题
        std::string star;   // 级别
        int cpu_limit;      // 时间
        int mem_limit;      // 内存
        std::string desc;   // 题目描述
        std::string header; // 题目预设
        std::string tail;   // 测试用例
    };

   const std::string questins_list = "./questions/questions.list";
   const std::string questins_path = "./questions/";
    class Models
    {
    private:
        unordered_map<string, struct Question> questions;

    public:
        Models()
        {

            assert(LoadQuestionList(questins_list));
        }
        bool LoadQuestionList(const std::string &question_list)
        {
           ifstream in(question_list);
           if(!in.is_open())
           {
           LOG(INFO)<<"请检查是否存在这个文件!"<<"\n";
            return false;
           }

           std::string line;
           while(getline(in,line))
           {
            std::vector<string> tokens;
            StringUtil::SplitString(line,&tokens," ");
            if(tokens.size()!=5)
            {
                continue;
            }
            Question q;
            q.number=tokens[0];
            q.title=tokens[1];
            q.star=tokens[2];
            q.cpu_limit=atoi(tokens[3].c_str());
            q.mem_limit=atoi(tokens[4].c_str());

            string path=questins_path;
            path+=q.number;
            path+="/";
            FileUtil::ReadFile(path+"desc.txt",&(q.desc),true);
            FileUtil::ReadFile(path+"header.cpp",&(q.header),true);
            FileUtil::ReadFile(path+"tail.cpp",&(q.tail),true);
            questions.insert({q.number,q});
             LOG(INFO)<<"加载题目："<<q.title<<std::endl;
             }
           LOG(INFO)<<"加载所有题目.....sucess!"<<"\n";
            in.close();
           return true;

        }
        bool GetAllQuestions(vector<Question> *out)
        {
            if(questions.size()==0)
            { 
                LOG(ERROR)<<"用户获取题目失败......!"<<"\n";
                return false;
            }
            else{
          for(const auto&q:questions)
          {
            out->push_back(q.second);
            LOG(WARNING)<<(q.second.title)<<"\n";
          }
          return true;
            }
        }
        bool GetOneQuestions(const std::string &number, Question *out)
        {
           const auto& iter=questions.find(number);
           if(iter==questions.end())
           {
             LOG(ERROR)<<"用户获取题目失败......!"<<"标题:"<<number<<"\n";
            return false;
           }
           (*out)=iter->second;
           return true;

        }
        ~Models() {};

    
    };

}